package com.hmdp.utils;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.constants.RedisConstant;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    设置过期时间以及数据
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

//    设置逻辑过期时间以及数据
    public void setWithLogicExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryWithPassThrough(String prefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                               Long time, TimeUnit unit ) {
        log.info("开始执行查找店铺过程");
        String key  = prefix + id;
//        从redis里面查询商铺缓存
        String json = stringRedisTemplate.opsForValue().get(key);

//  判断是否为空
//        如果存在，则直接返回
        if (StrUtil.isNotBlank(json)) {
            log.info("缓存中存在shop，返回shop");
            return JSONUtil.toBean(json, type);
        }
//          如果存在且不blank，但是为空字符串
        if(json != null){
            return null;
        }

        R r = dbFallback.apply(id);
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key, "", RedisConstant.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        this.set(key, r, time, unit);
        return r;

    }

    public <R, ID> R queryWithLogicExpire(String prefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                                          Long time, TimeUnit unit){
//        1.命中，现将json反序列化为对象

//        2.判断是否过期

//        2.1如果未过期，则返回

//        3.如果已过期，则缓存重建

//        3.1 获取互斥锁

//        3.2 判断是否获取成功

//        3.3 获取失败，代表有人正在重建，返回旧的值

//        3.4 获取成功
//        4.获取成功，创建独立线程，返回旧值，开始重建缓存

        String key  = prefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isBlank(json)) {
            log.info("缓存中不存在，返回fail");
            return null;
        }

        String lockKey = RedisConstant.LOCK_SHOP_KEY + id;

        try {
            RedisData redisData = JSONUtil.toBean(json, RedisData.class);
            JSONObject data = (JSONObject)redisData.getData();

            R r = JSONUtil.toBean(data, type);
            LocalDateTime expireTime = redisData.getExpireTime();

//            2.1如果未过期，则返回
            if(expireTime.isAfter(LocalDateTime.now())){
                log.info("缓存未过期，直接返回");
                return r;
            }

//            3.如果已过期，则缓存重建
//        3.3 获取失败，代表有人正在重建，返回旧的值
            boolean isLock = addLock(lockKey);
            if(!isLock){
                log.info("缓存已经过期，但是有人正在修改,因为已经上锁了");
                return r;
            }

//            获取成功了：
            log.info("缓存已经过期，开始重建");
            json = stringRedisTemplate.opsForValue().get(key);
            redisData = JSONUtil.toBean(json, RedisData.class);
            data = (JSONObject)redisData.getData();

            r = JSONUtil.toBean(data, type);
            expireTime = redisData.getExpireTime();

//            2.1重建 获取锁成功后，进行double check，如果未过期，则返回
            if(expireTime.isAfter(LocalDateTime.now())){
                log.info("缓存已更新，直接返回");
                return r;
            }

            R finalR = r;
            CACHE_REBUILD_EXECUTOR.submit(() -> {
//                4.获取成功，创建独立线程，返回旧值，开始重建缓存
                try {
                    this.setWithLogicExpire(key, finalR, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
//                4.1 释放锁
                    unLock(lockKey);
                }
            });
//                4.获取成功，创建独立线程，返回旧值
            return r;

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }

    }

    private boolean addLock(String key){
        Boolean flag =stringRedisTemplate.opsForValue().setIfAbsent(key, "LOCKING", 10, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    private void unLock(String key){
        Boolean flag =stringRedisTemplate.delete(key);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

}
